package com.xiaojian.pick.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaojian.pick.entity.CommodityComment;
import com.xiaojian.pick.mapper.CommodityCommentMapper;
import com.xiaojian.pick.service.CommodityCommentService;
import com.xiaojian.pick.service.CommodityService;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * @author whycode
 * @title: CommodityCommentServiceImpl
 * @projectName campus-secondary-market-app---sys
 * @description: TODO
 * @date 2022/3/2510:37
 */
@Service
public class CommodityCommentServiceImpl extends ServiceImpl<CommodityCommentMapper, CommodityComment> implements CommodityCommentService {

    @Resource
    @Lazy
    private CommodityService commodityService;

    @Override
    @Transactional
    public boolean save(CommodityComment entity) {
        boolean save = super.save(entity);
        if(save){
            commodityService.increaseComment(entity.getCid());
        }
        return save;
    }

    @Override
    public Page<CommodityComment> queryByPage(Integer cId, Integer page, Integer limit) {
        QueryWrapper<CommodityComment> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("cid", cId)
                .eq("reply_id", 0)
                .orderByDesc("time");
        Page<CommodityComment> commentPage = this.page(new Page<>(page, limit), queryWrapper);
        List<CommodityComment> records = commentPage.getRecords();
        if(records != null){
           records.forEach(record -> {
               record.setChildren(children(cId, record.getId()));
               record.setShow(false);
           });
        }
        commentPage.setRecords(records);
        return commentPage;
    }

    private List<CommodityComment> children(Integer cid, Integer replyId){
        List<CommodityComment> list = this.list(new QueryWrapper<CommodityComment>()
                .eq("cid", cid)
                .eq("reply_id", replyId)
                .orderByDesc("time"));
        if(list != null){
            List<CommodityComment> res = new ArrayList<>();
            for (int i = 0; i < list.size(); i++){
                CommodityComment comment = list.get(i);
                if(i == 0){
                    comment.setShow(true);
                }
                comment.setId(comment.getReplyId());
                res.add(comment);
            }
            list = res;
        }
        return list;
    }
}
